package com.zhenyi.youqu.interceptor;

import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.youqu.common.model.YqAppResource;
import com.youqu.common.model.YqShopUser;

import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;

public class HasEditPermissionFreeMarkerMethod implements TemplateMethodModelEx {

	private YqShopUser user;
	private Controller controller;

	public HasEditPermissionFreeMarkerMethod(YqShopUser staff, Controller controller) {
		this.user = staff;
		this.controller = controller;
	}

	// private final String disable = "style='pointer-events: none;'
	// disabled='disabled'";
	private final String disable = "disabled='disabled'";

	@Override
	public Object exec(@SuppressWarnings("rawtypes") List list) throws TemplateModelException {
		if (YqShopUser.ROLE_SUPER_ADMIN.equals(user.getRole())) {
			return "";
		}
		boolean readOnly = controller.getParaToInt("r", 0) == 1;
		if (readOnly) {
			return disable;
		}
		Integer YES = 1;
		Integer read = controller.getAttr("read");
		if (YES.equals(read)) {
			return disable;
		}
		if (null == list || 1 != list.size()) {
			throw new TemplateModelException("Wrong arguments: only one argument is allowed");
		}
		String permissionName = String.valueOf(list.get(0));
		Kv kv = Kv.by("name", permissionName);
		kv.set("userId", user.getId());
		SqlPara sqlPara = Db.use("youqu").getSqlPara("YqFindUserResource", kv);
		YqAppResource appResource = YqAppResource.dao.findFirst(sqlPara);
		if (appResource == null) {
			return disable;
		}
		Integer isNew = controller.getAttr("isNew");
		if (YES.equals(isNew)) {
			if (YES.equals(appResource.getCanNew())) {
				return "";
			}
		}
		if (YES.equals(appResource.getCanEdit())) {
			return "";
		}
		return disable;
	}
}
